package it.niedermann.android.markdown.markwon.span

import android.text.TextPaint
import android.text.style.ClickableSpan
import android.view.View
import io.noties.markwon.plugin.tasklist.span.TaskListSpan
import timber.log.Timber
import java.util.concurrent.atomic.AtomicBoolean
import java.util.function.BiConsumer

class ToggleTaskListSpan(
    private val enabled: AtomicBoolean,
    private val toggleListener: BiConsumer<Int, Boolean>,
    private val span: TaskListSpan,
    private val position: Int
) : ClickableSpan() {
    override fun onClick(widget: View) {
        if (enabled.get()) {
            span.isDone = !span.isDone
            widget.invalidate()
            toggleListener.accept(position, span.isDone)
        } else {
            Timber.tag(TAG).w("Prevented toggling checkbox because the view is disabled")
        }
    }

    override fun updateDrawState(ds: TextPaint) {
        // NoOp to remove underline text decoration
    }

    companion object {
        private val TAG = ToggleTaskListSpan::class.java.simpleName
    }
}